<template>
  <el-card>
    <upload-excel :on-success="handleSuccess" :before-upload="beforeUpload" />
  </el-card>
</template>

<script>
import { importEmployee } from '@/api/employees'
import { formatExcelDate } from '@/utils/index'
export default {
  name: 'Import',
  methods: {
    beforeUpload(file) {
      const isLt1M = file.size / 1024 / 1024 < 1

      if (isLt1M) {
        return true
      }

      this.$message({
        message: 'Please do not upload files larger than 1m in size.',
        type: 'warning'
      })
      return false
    },
    transformData(results) {
      const mapInfo = {
        '入职日期': 'timeOfEntry',
        '手机号': 'mobile',
        '姓名': 'username',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName',
        '聘用形式': 'formOfEmployment'
      }

      return results.map(item => {
        // Object.keys(item) ==> [入职时间,姓名]
        const zhKeys = Object.keys(item)
        const obj = {}
        zhKeys.forEach(el => {
          const enKey = mapInfo[el] //  mapInfo[el] : username
          if (enKey === 'timeOfEntry' || enKey === 'correctionTime') {
            obj[enKey] = new Date(formatExcelDate(item[el]))
          } else {
            obj[enKey] = item[el] // item[el] :  张三
          }

          console.log(obj[enKey])
        })
        return obj
      })
    },
    async  handleSuccess({ results, header }) {
    //   console.log('读取的数据', results)
    // 1.转格式: 按接口文档的要求
    //          (1)中文属性名转为英文
    //          (2) 日期时间,要额外处理
      const data = this.transformData(results)
      console.log(data)
      // 2. 调用接口 ,传入转换后的数据
      try {
        await importEmployee(data)
        this.$message.success('添加成功')
        this.$router.back()
      } catch (err) {
        this.$message.error(err.message)
      }
    }
  }
}
</script>
